package com.adee.primary.t01_arr;

import com.adee.util.Util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 两个数组的交集
 */
public class T006 {
    public static void main(String[] args) {
        int[] arr1 = {1,2,2,1};
        int[] arr2 = {2,2};
        Util.print(test1(arr1,arr2));
    }

    // 双指针解法
    // 先将两个数组排序，然后用双指针i、j比较
    //
    public static int[] test1(int[] arr1, int[] arr2) {
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        int i = 0, j = 0;
        List<Integer> list = new ArrayList<>();
        while (i < arr1.length && j < arr2.length) {
            if (arr1[i] < arr2[j]) {
                ++i;
            } else if (arr1[i] > arr2[j]) {
                ++j;
            }else {
                list.add(arr1[i]);
                ++i;
                ++j;
            }
        }
        int[] ret = new int[list.size()];
        int[] ints = list.stream().mapToInt(e -> e).toArray();
        return ints;
    }
}
